// lib/pages/msg.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_shop/models/msg.dart';
import 'package:multi_shop/pages/hat_detail_page.dart';
import 'package:multi_shop/utils/ws.dart';

enum NoticeType { order, logistics }

class MessageThread {
  final String id;
  final String name; // 商家名 / 客服
  final String avatar; // 头像
  final String lastMsg; // 最新一条
  final DateTime time; // 时间
  final int unread; // 未读数
  MessageThread({
    required this.id,
    required this.name,
    required this.avatar,
    required this.lastMsg,
    required this.time,
    required this.unread,
  });
}

class NoticeItem {
  final String id;
  final NoticeType type;
  final String title;
  final String content;
  final DateTime time;
  final bool unread;
  NoticeItem({
    required this.id,
    required this.type,
    required this.title,
    required this.content,
    required this.time,
    this.unread = true,
  });
}

class Msg extends StatefulWidget {
  const Msg({super.key});
  @override
  State<Msg> createState() => _MsgState();
}

class _MsgState extends State<Msg> with SingleTickerProviderStateMixin {
  NoticeType? _filter; // null=全部

  // ====== Mock 数据（替换为接口数据即可）======
  final List<MessageThread> _threads = [
    MessageThread(
      id: 's1',
      name: '苹果旗舰店',
      avatar: 'https://picsum.photos/seed/shop1/200/200',
      lastMsg: '您好，您咨询的 iPhone 已到货～',
      time: DateTime.now().subtract(const Duration(minutes: 5)),
      unread: 2,
    ),
    MessageThread(
      id: 's2',
      name: '牛奶自营店',
      avatar: 'https://picsum.photos/seed/shop2/200/200',
      lastMsg: '发票已开具，注意查收邮件',
      time: DateTime.now().subtract(const Duration(hours: 3)),
      unread: 0,
    ),
  ];
  // =======================================
  // 片段：进入页面时连接，仅文本输入发送
  final msgs = <MallChatMessage>[].obs;
  final inputCtrl = TextEditingController();

  @override
  void initState() {
    super.initState();
    chatWs.messages.listen((m) {
      msgs.add(m);
    });
  }

  @override
  void dispose() {
    chatWs.dispose();
    inputCtrl.dispose();
    super.dispose();
  }

  String _fmt(DateTime dt) {
    final now = DateTime.now();
    if (now.difference(dt).inDays >= 1) {
      return '${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}';
    }
    final h = dt.hour.toString().padLeft(2, '0');
    final m = dt.minute.toString().padLeft(2, '0');
    return '$h:$m';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('消息')),
      body: RefreshIndicator(
        onRefresh: () async {
          // TODO: 拉取最新会话
          await Future.delayed(const Duration(milliseconds: 500));
        },
        child: ListView.separated(
          padding: const EdgeInsets.symmetric(vertical: 8),
          itemCount: _threads.length,
          separatorBuilder: (_, __) =>
              Divider(height: 1, color: Colors.grey.withValues(alpha: 0.1)),
          itemBuilder: (ctx, i) {
            final t = _threads[i];
            return ListTile(
              onTap: () {
                Get.to(
                  () => ChatDetailPage(
                    threadId: t.id,
                    shopName: t.name,
                    shopAvatar: t.avatar,
                  ),
                );
              },
              leading: ClipOval(
                child: Image.network(
                  t.avatar,
                  width: 44,
                  height: 44,
                  fit: BoxFit.cover,
                  errorBuilder: (_, __, ___) => Container(
                    width: 44,
                    height: 44,
                    color: Colors.grey.withValues(alpha: 0.2),
                    child: const Icon(
                      Icons.store_mall_directory,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              title: Text(
                t.name,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(fontWeight: FontWeight.w600),
              ),
              subtitle: Text(
                t.lastMsg,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              trailing: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _fmt(t.time),
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  const SizedBox(height: 6),
                  if (t.unread > 0)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 6,
                        vertical: 2,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(
                        '${t.unread}',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.white,
                        ),
                      ),
                    ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
